package finallytest;

import java.util.ArrayDeque;
import java.util.Deque;

public class FinallyIssue {
	public static void main(String[] args) {
		Deque deque = new ArrayDeque();
		System.out.println("return value : " + finallyReturnTest(1));
		System.out.println("return value : " + finallyReturnTest(-1));
		System.out.println("finallyBreakTest : ");
		System.out.println("return value : " + finallyBreakTest(true));
		System.out.println("return value : " + finallyBreakTest(false));

		System.out.println("valueChangeInFinallyTest : ");
		System.out.println("return value : " + valueChangeInFinallyTest());

		System.out.println("valueChangeReturnInFinallyTest : ");
		System.out
				.println("return value : " + valueChangeReturnInFinallyTest());

		System.out.println("refValueChangeInFinallyTest : ");
		System.out.println("return name : "
				+ refValueChangeInFinallyTest().name);
	}

	private static boolean finallyReturnTest(int value) {
		try {
			if (value > 0) {
				return true;
			} else {
				return false;
			}
		} finally {
			return false;
		}
	}

	private static boolean finallyBreakTest(boolean value) {
		while (value) {
			try {
				return true;
			} finally {
				break;
			}
		}
		return false;
	}

	private static int valueChangeInFinallyTest() {
		int i = 10;
		int j = 1;
		try {
			i = 100;
			j = 2;
			System.out.println("try : i = " + i);
			System.out.println("try : j = " + j);
			Integer t = null;
//			j = t;
			return i;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			i = 1000;
			j = 3;
			System.out.println("finally : i = " + i);
			System.out.println("finally : j = " + j);
		}

		return i;
	}

	private static int valueChangeReturnInFinallyTest() {
		int i = 10;
		int j = 1;
		try {
			i = 100;
			j = 2;
			System.out.println("try : i = " + i);
			System.out.println("try : j = " + j);
			return i;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			i = 1000;
			j = 3;
			System.out.println("finally : i = " + i);
			System.out.println("finally : j = " + j);
			return i;
		}
	}

	private static Person refValueChangeInFinallyTest() {
		Person p = new Person();
		try {
			p.name = "person1";
			System.out.println("try : Person name is : " + p.name);
			return p;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			p.name = "person2";
			System.out.println("finally : Person name is : " + p.name);
		}

		p.name = "person3";
		System.out.println("out : Person name is : " + p.name);

		return p;
	}

	static class Person {
		public String name;
	}
}
